<template>
    <div>
        <el-form :model="form">
            <el-form-item label="用户名" :label-width="formLabelWidth">
                <el-input v-model="form.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="重复密码" :label-width="formLabelWidth" v-if="isReg">
                <el-input v-model="form.password2" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="验证码" :label-width="formLabelWidth" v-if="isReg">
                <el-input v-model="form.checkCode" autocomplete="off"></el-input>
            </el-form-item>
            <p v-if="!isReg">
                忘记密码
                <span @click="toReg">去注册</span>
            </p>
            <p v-if="isReg" @click="toLog">
                去登录
            </p>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="onSubmit">{{logType.title}}</el-button>
        </div>
    </div>
</template>

<script>
import { useUser } from "@/api";
import {mapMutations} from "vuex";
import tools from "@/tools";
export default {
    beforeRouteEnter (to, from, next) {
        next(vm=>{
            // 将来时的路由信息，绑定到实例身上，以备登录成功后，跳转使用
            vm.from = from;
        })
    },
    data(){
        return {
            formLabelWidth:"200px",
            form: {
                username: '',
                password: '',
                password2: '',
                checkCode: '',
            },
            logType: {
                title: "登录",
                type:"login"
            },
            isReg: false,
            pw: "",
        }
    },
    methods: {
        ...mapMutations({
            set_isLogin: "user/set_isLogin",
            set_username: "user/set_username",
            set_password: "user/set_password"
        }),
        toReg(){
            // 显示注册表单
            this.dialogFormVisible = true;
            this.logType.title = "注册";
            this.logType.type = "register";
            this.isReg = true;
            this.clearFormValue();
        },
        toLog(){
            // 显示登录表单
            this.dialogFormVisible = true;
            this.logType.title = "登录";
            this.logType.type = "login";
            this.isReg = false;
            this.clearFormValue();
        },
        onSubmit(){
            // 提交之后的功能
            // 计划在注册成功后，自动登录，所以需要将密码临时存储起来（注册成功后，用户名会自动返回）
            this.pw = this.form.password;

            // 使用平台的登录或注册接口
            useUser(this.logType.type, {
                username: this.form.username,
                password: this.form.password,
                repassword: this.form.password2
            }).then(res=>{
                // 登录或注册完成
                // console.log(res.data);

                // 登录或注册失败
                if(res.data.errorCode === -1){
                // 错误提示
                this.$message.error(res.data.errorMsg);
                }else if(this.logType.type === "login"){
                // 登录成功后要执行的功能
                this.loginSuccess(res.data.data)
                }else if(this.logType.type === "register"){
                // 注册成功后要执行的功能
                this.registerSuccess(res.data.data);
                };
            })

            this.clearFormValue();
        },
        loginSuccess(data){
            // 隐藏对话框
            this.dialogFormVisible = false;
            // 提示信息
            this.$message({
                message: '恭喜你，登录成功',
                type: 'success'
            });

            const d = new Date();
            d.setDate(d.getDate()+30);
            document.cookie = "isLogin=ok;expires="+d;

            // 登录成功后，将登录成功产生的信心，保存到状态管理器（vuex）中，以便将来在其他组件中使用
            // this.$store.commit("user/set_isLogin", "ok");
            this.set_isLogin("ok");

            // this.$store.commit("user/set_username", data.username);
            this.set_username(data.username);

            // this.$store.commit("user/set_password", tools.getCookie("token_pass"));
            this.set_password(tools.getCookie("token_pass"))

            // 登录成功后，修改视图上的用户名信息
            // this.username = this.$store.state.user.username;

            // 登录成功后，要跳转到来时的路由
            this.$router.push(this.from.path);
        },
        registerSuccess(data){
            this.dialogFormVisible = false;
            this.$message({
                message: '恭喜你，注册成功',
                type: 'success'
            });
            // 注册成功后，自动登录
            useUser("/login", {
                username: data.username,
                password: this.pw
            }).then(res=>{
                if(res.data.errorCode === -1){
                this.$message.error(res.data.errorMsg);
                }else{
                this.loginSuccess(res.data.data)
                }
            })
        },
        clearFormValue(){
            this.form.username = "";
            this.form.password = "";
            this.form.password2 = "";
            this.form.checkCode = "";
        }
    }
}
</script>